package com.xframe.domain.knowledgeBase;

import com.xframe.domain.BaseModel;
import com.xframe.domain.ModelErrorCode;
import com.xframe.domain.repository.SysBaseRepository;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.domain.role.SysUser;
import com.xframe.xdal.core.DataBaseAccess;
import com.xframe.xdal.core.annotation.AutoFill;
import com.xframe.xdal.core.annotation.XAction;
import com.xframe.xdal.core.annotation.XColumn;
import com.xframe.xdal.core.annotation.XTable;
import com.xframe.xdal.core.constant.AutoFillType;
import com.xframe.xdal.core.exception.DalFrameException;
import com.xframe.xdal.core.model.ConditionValue;
import com.xframe.xdal.core.model.FindOptions;
import com.xframe.xdal.core.model.UpdateAttr;
import com.xframe.xdal.core.model.UpdateWhereMode;
import com.xframe.xdal.core.model.mapping.TableInfoBuilder;
import com.xframe.xdal.core.tran.XTransaction;
import com.xframe.xdal.core.util.IdCreateUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.commons.io.FilenameUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Data
@Accessors(chain=true)
@XTable(value = "repair_work_order", label = "维修单")
public class RepairWorkOrder extends BaseModel{
    /**
     * 主键ID
     */
    @AutoFill(AutoFillType.Snowflake)
    @XColumn(name = "rep_id",primaryKeyFlag = true,desc = "主键ID")
    private Long repId;


    @XColumn(name = "em_id",desc = "设备ID")
    private Long emId;


    /**
     *  是否入库
     */
    @XColumn(name = "is_warehouse",desc = "是否入库")
    private Integer isWarehouse;

    /**
     * 批准维修工单并创建相应的知识库条目。
     * @param repository 系统的基础仓库对象，用于数据访问。
     * @param userCredentials 当前用户的认证信息。
     * @return 更新的工单数量。
     * @throws DalFrameException 数据访问框架异常。
     * @throws ParseException 解析异常。
     */
    @XTransaction
    @XAction(code = "ratify", desc = "批准")
    public Integer ratify(SysBaseRepository repository, IUserCredentials userCredentials) throws DalFrameException, ParseException {
        // 获取维修详情
        VRepairDetail vRepairDetail = repository.getDataBaseAccess().findByPk(VRepairDetail.class, this.repId);
        if(vRepairDetail == null){
            throw new DalFrameException(ModelErrorCode.DATA_NOT_FOUND,ModelErrorCode.DATA_NOT_FOUND_TEXT);
        }
        // 创建知识库条目
        KnowledgeBase knowledgeBase = createKnowledgeBaseEntry(vRepairDetail, userCredentials);


        FindOptions findOptions = new FindOptions();
        findOptions.addConditionValue(new ConditionValue("busTablesId",vRepairDetail.getRepId()));
        findOptions.addConditionValue(new ConditionValue("busType",4));
        List<EmpBuisinessFile> empBuisinessFiles = DataBaseAccess.getInstance().findAll(EmpBuisinessFile.class,findOptions);


        List<KnowledgeFiles> knowledgeFilesList = new ArrayList<>();
        if(empBuisinessFiles != null && !empBuisinessFiles.isEmpty()){
            for(EmpBuisinessFile empBuisinessFile : empBuisinessFiles){
                EmpFile empFile = DataBaseAccess.getInstance().findByPk(EmpFile.class,empBuisinessFile.getFileCode(),"ALL");
                if(empFile != null){
                    KnowledgeFiles knowledgeFiles = new KnowledgeFiles();
                    knowledgeFiles.setFileName(empFile.getFileName());
                    knowledgeFiles.setFileUrl(empBuisinessFile.getFileCode());
                    knowledgeFiles.setKnId(knowledgeBase.getKnId());
                    knowledgeFiles.setFileCategory(empBuisinessFile.getFileType());

                    String extension = FilenameUtils.getExtension(empFile.getFileName());
                    knowledgeFiles.setFileType(extension);

                    knowledgeFilesList.add(knowledgeFiles);
                }

            }
        }


        // 更新系统参数
        SysPam sysPam = repository.getDataBaseAccess().findByPk(SysPam.class, 1);
        if(sysPam == null){
            throw new DalFrameException(ModelErrorCode.DATA_NOT_FOUND,ModelErrorCode.DATA_NOT_FOUND_TEXT);
        }
        updateSystemParameters(repository,sysPam, userCredentials);

        // 设置知识库代码
        setKnowledgeBaseCode(knowledgeBase, sysPam);

        // 存储知识库信息
        repository.getDataBaseAccess().createNew(knowledgeBase, KnowledgeBase.class);


        if(!knowledgeFilesList.isEmpty()){
            repository.getDataBaseAccess().batchCreate(KnowledgeFiles.class,knowledgeFilesList);
        }

        // 更新工单信息
        this.setBaseAttrVal(userCredentials);
        this.isWarehouse = 0;
        UpdateAttr updateAttr = new UpdateAttr(UpdateWhereMode.PK);
        updateAttr.addfieldName("isWarehouse");

        return repository.update(this, TableInfoBuilder.BuildTableInfoByAnnotation(RepairWorkOrder.class), updateAttr);
    }

    /**
     * 创建知识库条目
     */
    private KnowledgeBase createKnowledgeBaseEntry(VRepairDetail vRepairDetail, IUserCredentials userCredentials) {
        KnowledgeBase knowledgeBase = new KnowledgeBase();
        knowledgeBase.setKnId(IdCreateUtil.getSnowflakeId());
        knowledgeBase.setDocId(vRepairDetail.getRepId());
        knowledgeBase.setEmId(vRepairDetail.getEmId());
        knowledgeBase.setEmName(vRepairDetail.getEmName());
        knowledgeBase.setFaultPho(vRepairDetail.getRepFaultType());
        knowledgeBase.setFaultReason(vRepairDetail.getMtcFaultReason());
        knowledgeBase.setFaultType(vRepairDetail.getMtcFaultType());
        knowledgeBase.setWorkOrderCode(vRepairDetail.getWorkOrderCode());
        knowledgeBase.setKnStatus(1);
        knowledgeBase.setBaseAttrVal(userCredentials);
        knowledgeBase.setKnRepairBy(vRepairDetail.getMaintenEmployeeId());
        return knowledgeBase;
    }

    /**
     * 更新系统参数
     */
    private void updateSystemParameters(SysBaseRepository repository,SysPam sysPam, IUserCredentials userCredentials) throws ParseException {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String formattedDate = dateFormat.format(currentDate);
        SimpleDateFormat fullDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (fullDateFormat.parse(formattedDate).compareTo(sysPam.getUpdateTime()) > 0) {
            sysPam.setPamNum(1);
        } else {
            sysPam.setPamNum(sysPam.getPamNum() + 1);
        }

        sysPam.setBaseAttrVal(userCredentials);
        UpdateAttr updateAttr = new UpdateAttr(UpdateWhereMode.PK);
        updateAttr.addfieldName(BaseModel.UPDATEBY_NAME).addfieldName(BaseModel.UPDATETIME_NAME).addfieldName("pamNum");

        repository.update(sysPam, TableInfoBuilder.BuildTableInfoByAnnotation(SysPam.class), updateAttr);
    }

    /**
     * 设置知识库代码
     */
    private void setKnowledgeBaseCode(KnowledgeBase knowledgeBase, SysPam sysPam) {
        SimpleDateFormat sdf = new SimpleDateFormat("-yyyyMMdd-");
        String formattedDate = sdf.format(new Date());
        knowledgeBase.setKnCode("ZSK" + formattedDate + String.format("%03d", sysPam.getPamNum()));
    }

    @XTransaction
    @XAction(code = "refuse",desc = "拒绝")
    public Integer refuse(SysBaseRepository repository, IUserCredentials userCredentials) throws DalFrameException {
        this.isWarehouse = 2;
        this.setBaseAttrVal(userCredentials);
        UpdateAttr updateAttr = new UpdateAttr(UpdateWhereMode.PK);
        updateAttr.addfieldName("isWarehouse");
        return repository.update(this, TableInfoBuilder.BuildTableInfoByAnnotation(RepairWorkOrder.class), updateAttr);
    }
}
